/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tomica.ws;

import iaik.pkcs.pkcs11.TokenException;
import iaik.pkcs.pkcs11.wrapper.CK_ATTRIBUTE;
import iaik.pkcs.pkcs11.wrapper.PKCS11Constants;
import iaik.pkcs.pkcs11.wrapper.PKCS11Exception;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import ostt1_TokenLib.ostt1_TokenLib;
import tomica.datarespone.C_GetSlotList_Response;
import tomica.datarespone.DataResponse_C_FindObjects;
import tomica.datarespone.DataResponse_C_GetAttributeValue;
import tomica.datarespone.DataResponse_C_GetInfo;
import tomica.datarespone.DataResponse_C_GetMechanismList;
import tomica.datarespone.DataResponse_C_GetSlotInfo;
import tomica.datarespone.DataResponse_C_GetTokenInfo;
import tomica.datarespone.DataResponse_C_OpenSession;
import tomica.exception.PKCS11Exception_Tomica_ext;

/**
 *
 * @author Tcchtnn (nhantv@tomicalab.com)
 */
@WebService(serviceName = "MiniHSMWS")
public class MiniHSMWS {

    /**
     * This is a sample web service operation
     */
    @WebMethod(operationName = "hello")
    public String hello(@WebParam(name = "name") String txt) {
        return "Hello " + txt + " !";
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "testConnectToken")
    public int testConnectToken() {
        int a = -1;
        try {
            //TODO write your implementation code here:
            a = ostt1_TokenLib.testConnectToken();
        } catch (TokenException ex) {
            //Logger.getLogger(MiniHSMWS.class.getName()).log(Level.SEVERE, null, ex);
            a=100;
        } catch (GeneralSecurityException ex) {
            a = 101;
            //Logger.getLogger(MiniHSMWS.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            a = 102;
            //Logger.getLogger(MiniHSMWS.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            a = 103;
            //Logger.getLogger(MiniHSMWS.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("connect result: " + a);
        return a;
    }

    @WebMethod(operationName = "C_Initialize")
    public long C_Initialize() {
        System.out.println("Go C_Initialize.");
        //testConnectToken();

        long result = PKCS11Constants.CKR_OK;
        try {
            ostt1_TokenLib.p11initialize();
        } catch (IOException ex) {
            //Logger.getLogger(MiniHSMWS.class.getName()).log(Level.SEVERE, null, ex);
        } catch (PKCS11Exception ex) {
            result = ex.getErrorCode();
            System.out.println("[C_Initialize]exception : " + ex.getMessage());
        }
        System.out.println("[C_Initialize]result: " + result);
        return result;
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "C_Finalize")
    public long C_Finalize() {
        long result = PKCS11Constants.CKR_OK;
        try {
            ostt1_TokenLib.p11finalize();
        } catch (PKCS11Exception ex) {
            result = ex.getErrorCode();
        }
        return result;
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "C_GetSlotList")
    public C_GetSlotList_Response C_GetSlotList(@WebParam(name = "tokenPresent") boolean tokenPresent) {
        System.out.println("Go C_GetSlotList.");
        C_GetSlotList_Response response = new C_GetSlotList_Response();
        response.setResult_code(PKCS11Constants.CKR_OK);
        try {
            response.setSlotArray(ostt1_TokenLib.toCGetSlotList(tokenPresent));
        } catch (PKCS11Exception ex) {
            response.setResult_code(ex.getErrorCode());
        }
        System.out.println("[C_GetSlotList] count slot: " + response.getSlotArray().length);
        return response;
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "C_OpenSession")
    public DataResponse_C_OpenSession C_OpenSession(@WebParam(name = "slotID") long slotID) {

        System.out.println("Go C_OpenSession slot ID: "+ slotID);
        DataResponse_C_OpenSession result = new DataResponse_C_OpenSession();
        try {
            result.setSessionHandler(ostt1_TokenLib.toCOpenSession(slotID));
            result.setResult_code(PKCS11Constants.CKR_OK);
        } catch (PKCS11Exception ex) {
            //Logger.getLogger(MiniHSMWS.class.getName()).log(Level.SEVERE, null, ex);
            result.setResult_code(ex.getErrorCode());
        }
        System.out.println("[C_OpenSession]handleSession: " + result.getSessionHandler());
        return result;
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "C_CloseSession")
    public long C_CloseSession(@WebParam(name = "hSession") final long hSession) {
        long result = PKCS11Constants.CKR_OK;
        try {
            ostt1_TokenLib.toCCloseSession(hSession);
        } catch (PKCS11Exception ex) {
            //Logger.getLogger(MiniHSMWS.class.getName()).log(Level.SEVERE, null, ex);
            result = ex.getErrorCode();
        } catch (PKCS11Exception_Tomica_ext ex) {
            //Logger.getLogger(MiniHSMWS.class.getName()).log(Level.SEVERE, null, ex);
            result = ex.getErrorCode_();
        }
        return result;
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "C_Login")
    public long C_Login(@WebParam(name = "hSession") final long hSession, @WebParam(name = "userType") long userType, @WebParam(name = "oin") byte[] pin, @WebParam(name = "lengthPin") long lengthPin) {
        long result = PKCS11Constants.CKR_OK;
        System.out.println("[C_Login] string: " + pin.toString());
        try {
            ostt1_TokenLib.toCLogin(hSession, pin, userType);
            //System.out.println("run getEnumPri: "+ostt1_TokenLib.GetEnumPri(0));
        } catch (PKCS11Exception ex) {            
            result = ex.getErrorCode();
        } catch (PKCS11Exception_Tomica_ext ex) {            
            result = ex.getErrorCode_();
        }
        
        System.out.println("[C_Login] out");
        return result;
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "C_Logout")
    public long C_Logout(@WebParam(name = "hSession") final long hSession) {
        System.out.println("[C_Logout] hSession: " + hSession);
        long result = PKCS11Constants.CKR_OK;
        try {
            ostt1_TokenLib.toCLogOut(hSession);
        } catch (PKCS11Exception ex) {
            //Logger.getLogger(MiniHSMWS.class.getName()).log(Level.SEVERE, null, ex);
            result = ex.getErrorCode();
        } catch (PKCS11Exception_Tomica_ext ex) {
            //Logger.getLogger(MiniHSMWS.class.getName()).log(Level.SEVERE, null, ex);
            result = ex.getErrorCode_();
        }
        System.out.println("[C_Logout] ");
        return result;
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "C_GetTokenInfo")
    public DataResponse_C_GetTokenInfo C_GetTokenInfo(@WebParam(name = "slotID") final long slotID) {
        DataResponse_C_GetTokenInfo result = new DataResponse_C_GetTokenInfo();
        try {
            result.setTokenInfor(ostt1_TokenLib.toCGetTokenInfor(slotID));
            result.setResponseCode(PKCS11Constants.CKR_OK);
        } catch (PKCS11Exception ex) {
            //Logger.getLogger(MiniHSMWS.class.getName()).log(Level.SEVERE, null, ex);
            result.setResponseCode(ex.getErrorCode());
        }
        System.out.println("[C_GetTokenInfo]out ");
        return result;
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "C_FindObjectsInit")
    public long C_FindObjectsInit(@WebParam(name = "hSession") final long hSession, @WebParam(name = "ulCount") final long ulCount, @WebParam(name = "pTemplate") CK_ATTRIBUTE[] pTemplate) {

        System.out.println("[C_FindObjectsInit] hSession: " + hSession);
        System.out.println("[C_FindObjectsInit] sizepTemplate: " + pTemplate.length);
        long result = PKCS11Constants.CKR_OK;
        try {
            ostt1_TokenLib.toCFindObjectsInit(hSession, pTemplate);
        } catch (PKCS11Exception ex) {
            result = ex.getErrorCode();
        } catch (PKCS11Exception_Tomica_ext ex) {
            //Logger.getLogger(MiniHSMWS.class.getName()).log(Level.SEVERE, null, ex);
            result = ex.getErrorCode_();
        }
        return result;
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "C_FindObjects")
    public DataResponse_C_FindObjects C_FindObjects(@WebParam(name = "hsession") final long hsession, @WebParam(name = "maxobject") long maxobject) {
        DataResponse_C_FindObjects result = new DataResponse_C_FindObjects();

        try {
            result.setReturnHandle(ostt1_TokenLib.toCFindObjects(hsession, maxobject));
            result.setResponseCode(PKCS11Constants.CKR_OK);
        } catch (PKCS11Exception ex) {
            //Logger.getLogger(MiniHSMWS.class.getName()).log(Level.SEVERE, null, ex);
            result.setResponseCode(ex.getErrorCode());
        } catch (PKCS11Exception_Tomica_ext ex) {
            //Logger.getLogger(MiniHSMWS.class.getName()).log(Level.SEVERE, null, ex);
            result.setResponseCode(ex.getErrorCode_());
        }
        if (result.getReturnHandle() != null) {
            System.out.println("[C_FindObjects] handle size: "+ result.getReturnHandle().length);
//            if (result.getReturnHandle().length <1) {
//                result.setResponseCode(PKCS11Constants.CKR_DATA_INVALID);
//            }
        }
        return result;
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "C_FindObjectsFinal")
    public long C_FindObjectsFinal(@WebParam(name = "hSession") final long hSession) {
        System.out.println("[C_FindObjectsFinal] hSession: " + hSession);

        long result = PKCS11Constants.CKR_OK;
        try {
            ostt1_TokenLib.toCFindObjectsFinal(hSession);
        } catch (PKCS11Exception ex) {
            result = ex.getErrorCode();
        } catch (PKCS11Exception_Tomica_ext ex) {
            //Logger.getLogger(MiniHSMWS.class.getName()).log(Level.SEVERE, null, ex);
            result = ex.getErrorCode_();
        }
        return result;
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "C_GetAttributeValue")
    public DataResponse_C_GetAttributeValue C_GetAttributeValue(@WebParam(name = "hSession") final long hSession, @WebParam(name = "hObject") long hObject,
            @WebParam(name = "pTemplate") CK_ATTRIBUTE[] pTemplate, @WebParam(name = "ulCount") final long ulCount) {
        System.out.println("[C_GetAttributeValue] hSession: " + hSession);

        DataResponse_C_GetAttributeValue result = new DataResponse_C_GetAttributeValue();

        try {
            result.setAttributeList(ostt1_TokenLib.toCGetAttributes(hSession, hObject, pTemplate));
            //ostt1_TokenLib.toCGetAttributes(hSession, hObject, pTemplate);
            result.setResponseCode(PKCS11Constants.CKR_OK);
        } catch (PKCS11Exception ex) {
            //Logger.getLogger(MiniHSMWS.class.getName()).log(Level.SEVERE, null, ex);
            result.setResponseCode(ex.getErrorCode());
        } catch (PKCS11Exception_Tomica_ext ex) {
            //Logger.getLogger(MiniHSMWS.class.getName()).log(Level.SEVERE, null, ex);
            result.setResponseCode(ex.getErrorCode_());
        }
        //System.out.println("[C_FindObjects] handle size: "+ result.getReturnHandle().length);
        return result;

    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "C_SetPIN")
    public long C_SetPIN(@WebParam(name = "hSession") final long hSession, @WebParam(name = "pOldPin") byte[] pOldPin, @WebParam(name = "ulOldPin") long ulOldPin, @WebParam(name = "pNewPin") byte[] pNewPin, @WebParam(name = "ulNewPin") long ulNewPin) {
        System.out.println("[C_SetPIN] hSession: " + hSession);

        long result = PKCS11Constants.CKR_OK;
        try {
            ostt1_TokenLib.toCSetPin(hSession, pOldPin, pNewPin);
        } catch (PKCS11Exception ex) {
            result = ex.getErrorCode();
        } catch (PKCS11Exception_Tomica_ext ex) {
            //Logger.getLogger(MiniHSMWS.class.getName()).log(Level.SEVERE, null, ex);
            result = ex.getErrorCode_();
        }

        return result;
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "C_GetInfo")
    public DataResponse_C_GetInfo C_GetInfo() {
        System.out.println("[C_GetInfo] ");
        DataResponse_C_GetInfo result = new DataResponse_C_GetInfo();
        try {           
            result.setInfo(ostt1_TokenLib.toCGetInfo());
            result.setResponseCodeBi(PKCS11Constants.CKR_OK);
        } catch (PKCS11Exception ex) {
            //Logger.getLogger(MiniHSMWS.class.getName()).log(Level.SEVERE, null, ex);
            result.setResponseCodeBi(ex.getErrorCode());
        }
        return result;
    }
    
    /**
     * Web service operation
     */
    @WebMethod(operationName = "C_GetSlotInfo")
    public DataResponse_C_GetSlotInfo C_GetSlotInfo(@WebParam(name = "slotID") final long slotID) {
        System.out.println("[C_GetSlotInfo] slot ID: "+slotID);
        DataResponse_C_GetSlotInfo result = new DataResponse_C_GetSlotInfo();
        try {           
            result.setSlotInfor(ostt1_TokenLib.toCGetSlotInfo(slotID));
            result.setResponseCode(PKCS11Constants.CKR_OK);
        } catch (PKCS11Exception ex) {
            //Logger.getLogger(MiniHSMWS.class.getName()).log(Level.SEVERE, null, ex);
            result.setResponseCode(ex.getErrorCode());
        }
        System.out.println("[C_GetSlotInfo] out: "+slotID);
        return result;
    }
    
    /**
     * Web service operation
     */
    @WebMethod(operationName = "C_GetMechanismList")
    public DataResponse_C_GetMechanismList C_GetMechanismList(@WebParam(name = "slotID") final long slotID) {
        System.out.println("Go C_GetMechanismList.");
        DataResponse_C_GetMechanismList response = new DataResponse_C_GetMechanismList();
        response.setResponseCode(PKCS11Constants.CKR_OK);
        try {
            response.setpMechanismList(ostt1_TokenLib.toC_GetMechanismList(slotID));
        } catch (PKCS11Exception ex) {
            response.setResponseCode(ex.getErrorCode());
        }
        System.out.println("[C_GetMechanismList] count mechanisms: " + response.getpMechanismList().length);
        return response;
    }
    
    
    
    
    
    
}
